package com.jack.charging.order.quartz;

import com.jack.charging.order.dao.repository.OrderRepository;
import com.jack.charging.order.pojo.po.ChargingBillFail;
import com.jack.charging.order.pojo.po.ChargingBillSuccess;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

/**
 * @author Jack
 * @date 2025/2/13 11:33
 * @see
 * @since
 */
@Slf4j
public class DeviceCheckJob implements Job {

    public DeviceCheckJob() {
        log.debug("DeviceCheckJob被调用");
    }
    public DeviceCheckJob(String orderNo) throws SchedulerException {
        log.debug("创建设备检查任务");
        // 创建scheduler实例
        Scheduler scheduler= StdSchedulerFactory.getDefaultScheduler();
        // 创建JobDetail实例
        JobDetail jobDetail = JobBuilder.newJob(DeviceCheckJob.class)
                .withIdentity("deviceCheckJob", "deviceCheckJobGroup")
                .build();
        // 创建Trigger实例 (触发器) 1分钟后执行且仅执行一次
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("deviceCheckTrigger", "deviceCheckTriggerGroup")
                .usingJobData("orderNo", orderNo)
                .startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.MINUTE))
//                .startNow()
//                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
//                        .withIntervalInSeconds(60)
//                        .repeatForever())
                .build();
        // 将任务和触发器添加到调度器中
        scheduler.scheduleJob(jobDetail, trigger);
        // 启动调度器
        scheduler.start();
    }
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.debug("DeviceCheckJob被执行");
        String orderNo = jobExecutionContext.getJobDetail().getJobDataMap().getString("orderNo");
        OrderRepository orderRepository = SpringContextUtils.getBean(OrderRepository.class);
        log.debug("查询订单成功订单记录，订单号:{}", orderNo);
        ChargingBillSuccess chargingBillSuccess = orderRepository.getChargingBillSuccessByOrderNo(orderNo);
        log.debug("查询订单成功订单记录，订单号:{},chargingBillSuccess:{}", orderNo, chargingBillSuccess);
        if (chargingBillSuccess == null) {
            log.debug("查询的订单号:{}不存在", orderNo);
            ChargingBillFail chargingBillFail = orderRepository.getChargingBillFailByOrderNo(orderNo);
            if (chargingBillFail == null) {
                log.debug("查询的失败订单号:{}不存在", orderNo);
                chargingBillFail = new ChargingBillFail();
                chargingBillFail.setBillId(orderNo);
                chargingBillFail.setFailDesc("设备没有响应");
                int row = orderRepository.insertFailOrder(chargingBillFail);
                log.debug("chargingBillFail:{},row:{}", chargingBillFail, row);
            }else{
                log.debug("有失败订单记录，无需处理");
            }
        }else{
            log.debug("有成功订单记录，无需处理");
        }
    }
}
